package org.jeecg.modules.cascv.image.service.merge;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.HexUtil;
import com.NativeImageIO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.net.www.content.image.png;

import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
@Slf4j
public class WurongqiweikongService extends ImageService {
    @Value("${imageurl}")
    private String imageurl;

    @Override
    public String idsNames() {
        return "TGTHYY0401_090H_31_CMPRAPP9,6D9DH_3FH,6D9DH_3FH";
    }

    @Autowired
    private TaskExecutePool taskExecutePool;


    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");


        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }


        String frames_field = LaptopConstant.FRAME_FIELD_MAP.get(idsName);
        String dataFrames = conJson.getString(frames_field);

        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);

        String data_type = conJson.getString("A1_CMPR_MICU_APP10DATA_16_16_1").split(";")[0];
        String package_type = conJson.getString("A1_CMPR_MICU_APP10DATA_17_17_1").split(";")[0];
        String image_no = conJson.getString("A1_CMPR_MICU_APP10DATA_18_19_1").split(";")[1];
        //dataFrames = dataFrames.substring(7, dataFrames.length() - 10);
        dataFrames= dataFrames.split(";")[1];
        dataFrames = dataFrames.substring(2).trim();
        StringBuilder queue = LaptopConstant.imageData.get(key);

        if ((StringUtils.equals("0x22", data_type) || StringUtils.equals("0x33", data_type)
                || StringUtils.equals("0x44", data_type) || StringUtils.equals("0x55", data_type))
                && StringUtils.equals("0x00", package_type) && StringUtils.equals("0000H", image_no)) {
            if (queue != null) {
                queue.append(dataFrames);
                if (queue.length() > 2006 * 2) {
                    composite(queue, conJson, idsName, key, secondStr, subSecondStr);
                }
            }
            queue = new StringBuilder();
            LaptopConstant.imageData.put(key, queue);
            queue.append(dataFrames);
            return null;
        }

        if (queue != null) {
            queue.append(dataFrames);
            return null;
        }

        return null;
    }


    private boolean composite(StringBuilder sb, JSONObject content, String idsName, String key, String secondStr, String subSecondStr) {
        boolean removeHeader = false;
        boolean removePre = false;

        String widthStr = sb.substring(0, 8);
        String heightStr = sb.substring(8, 16);
        Integer width = Integer.parseUnsignedInt(widthStr, 16);
        Integer height = Integer.parseUnsignedInt(heightStr, 16);
        int imageSize = width * height;

        String headerStr = sb.substring(0, 48);
//        Map<String, String> headerMap = HeaderUtil.parseGaowengui(headerStr);
        sb = sb.delete(0, 48);

        int oneCanSize = 4004;

        int headerSize = 0;

        ByteBuffer byteBuf = ByteBuffer.allocateDirect(imageSize);
        int writeIndex = 0;

        int i = 0;

        while (true) {
            if (sb.length() < oneCanSize) {
                break;
            }
            String oneCanStr = sb.substring(0, oneCanSize);
            System.out.println(oneCanStr.substring(0, 20));
            //拿到oneCanStr后，将其从sb中删除
            sb.delete(0, oneCanSize);


            byte[] bytes = HexUtil.decodeHex(oneCanStr.substring(headerSize));
            int writeLen = bytes.length;
            if (writeIndex + writeLen > imageSize) {
                writeLen = imageSize - writeIndex;
                byteBuf.put(ArrayUtil.sub(bytes, 0, writeLen));
            } else {
                byteBuf.put(bytes);
                System.out.println("add=" + bytes.length);
            }
            writeIndex += writeLen;
            if (writeIndex > imageSize) {
                break;
            }
            System.out.println(i++);
        }

        if (writeIndex < imageSize) {
            String oneCanStr = sb.substring(headerSize, (imageSize - writeIndex) * 2 + headerSize);
            byte[] bytes = HexUtil.decodeHex(oneCanStr);
            byteBuf.put(bytes);
        }

//        合成成功ImageTask(id=41560151012334,15453, framesType=1, packageTotalNum=19, headerIndex=1316, totalLength=37136, needMergeType=2, startId=41560151012334,15453, endId=41560151012414,15471, startEndFlag=1, idsName=TGTHYY0401_090H_31_CMPRAPP5, pgTy=cg, dataType=null, delFlag=0, width=192, height=192, planTime=1668577360137, dcNo=SD00, taskNo=22111611, retry=1, cost=0, costStart=1668577363724, iocost=58, createTime=1668577363672, imageNo=null, taskType=1, forceCreateImage=0, secondKey=null, zdyMap={A1_CMPR_MICU_APP5DATA_ZDY_1=0000b2eaH;45802;图像帧数;否, A1_CMPR_MICU_APP5DATA_ZDY_2=01H;01H;标识;否, A1_CMPR_MICU_APP5DATA_ZDY_3=0000000000H;0000000000H;填充;否, A1_CMPR_MICU_APP5DATA_ZDY_4=0001H;0001H;载荷类型;否, A1_CMPR_MICU_APP5DATA_ZDY_10=00000088H;136;y偏移;否, A1_CMPR_MICU_APP5DATA_ZDY_5=0000009d757547e4H;5410243886880;时间戳;否, A1_CMPR_MICU_APP5DATA_ZDY_6=01080001H;01080001H;图片格式;否, A1_CMPR_MICU_APP5DATA_ZDY_7=000000c0H;192;宽;否, A1_CMPR_MICU_APP5DATA_ZDY_8=000000c0H;192;高;否, A1_CMPR_MICU_APP5DATA_ZDY_9=000000e0H;224;x偏移;否, A1_CMPR_MICU_APP5DATA_ZDY_12=0000H;0;Padding-y;否, A1_CMPR_MICU_APP5DATA_ZDY_11=0000H;0;Padding-x;否}, imageType=null, wei_sheng=0, imgModel=null, firstNo=null, offSet=null, stepNos=null, imgNum=null, packageNo=null)
//        合成成功ImageTask(id=41560151012254,15434, framesType=1, packageTotalNum=20, headerIndex=3272, totalLength=37136, needMergeType=2, startId=41560151012254,15434, endId=41560151012334,15453, startEndFlag=1, idsName=TGTHYY0401_090H_31_CMPRAPP5, pgTy=cg, dataType=null, delFlag=0, width=192, height=192, planTime=1668577360137, dcNo=SD00, taskNo=22111611, retry=1, cost=0, costStart=1668577363724, iocost=62, createTime=1668577363653, imageNo=null, taskType=1, forceCreateImage=0, secondKey=null, zdyMap={A1_CMPR_MICU_APP5DATA_ZDY_1=0000b2e9H;45801;图像帧数;否, A1_CMPR_MICU_APP5DATA_ZDY_2=01H;01H;标识;否, A1_CMPR_MICU_APP5DATA_ZDY_3=0000000000H;0000000000H;填充;否, A1_CMPR_MICU_APP5DATA_ZDY_4=0001H;0001H;载荷类型;否, A1_CMPR_MICU_APP5DATA_ZDY_10=00000088H;136;y偏移;否, A1_CMPR_MICU_APP5DATA_ZDY_5=0000009d75708314H;5410241386656;时间戳;否, A1_CMPR_MICU_APP5DATA_ZDY_6=01080001H;01080001H;图片格式;否, A1_CMPR_MICU_APP5DATA_ZDY_7=000000c0H;192;宽;否, A1_CMPR_MICU_APP5DATA_ZDY_8=000000c0H;192;高;否, A1_CMPR_MICU_APP5DATA_ZDY_9=000000e0H;224;x偏移;否, A1_CMPR_MICU_APP5DATA_ZDY_12=0000H;0;Padding-y;否, A1_CMPR_MICU_APP5DATA_ZDY_11=0000H;0;Padding-x;否}, imageType=null, wei_sheng=0, imgModel=null, firstNo=null, offSet=null, stepNos=null, imgNum=null, packageNo=null)
        CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
            long start = System.currentTimeMillis();
            byteBuf.flip();
                byte[] arr = new byte[imageSize];
                if (byteBuf.limit() < imageSize) {
                    System.out.println("长度不足");
                }
                byteBuf.get(arr);
                String idStr = IdWorker.getIdStr();
                LaptopConstant.nativeImageIO.write(arr, height, width, "/data/images/", idStr + ".png", " png ");
                String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                System.out.println("imageUrl = " + imageUrl);
                // String base64 = Base64.getEncoder().encodeToString(arr);
                content.put("imageUrl", imageUrl);
                content.put("idsName", idsName);
                //String secondStr = content.getString(LaptopConstant.SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                //String subSecondStr = content.getString(LaptopConstant.SUB_SECOND_FIELD_MAP.get(idsName)).split(";")[1];
                String[] split = secondStr.split(":");
                content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                //content.put("fileId", key);
                content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
//                List<JSONObject> jsonObjectList = new CopyOnWriteArrayList<>();
//                jsonObjectList.add(content);
                content.put("key", key);
            log.info("无容器位控板卡图像"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

                return content;
            },taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);

        return true;
    }


    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        List<String> strings = FileUtil.readUtf8Lines("E:\\11图像数据\\cut\\无容器\\T20230407093923_0001_0090_F1_00_6DCD_2024_003F_3F_6D9D_000000000.txt");
        WurongqiweikongService test = new WurongqiweikongService();
        for (String string : strings) {
            JSONObject jsonObject = JSONObject.parseObject(string);
            test.merge(jsonObject, "6D9DH_3FH", "6D9DH_3FH");
        }
    }
}
